package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC564 {
    public long startExecuteTime = System.currentTimeMillis();


    /**
     * 有意思或者没有意思的纯数学题
     * n的一半的回文数
     * n的一半+1的回文数
     * n的一半-1的回文数
     * n的降一位最大回文数
     * n的升一位最小回文数
     * <p>
     * 这5个数之间，与n差的绝对值最小的数，就是答案
     */
    class Solution {
        public String nearestPalindromic(String n) {
            long len = n.length();
            if (len == 1) {
                return String.valueOf(Integer.valueOf(n) - 1);
            }
            long me = Long.valueOf(n);
            boolean odd = (len & 1) == 1;
            long half = (len + 1) >> 1;
            char[] cs = n.toCharArray();
            long h = 0;
            int p = 0;
            while (p < half) {
                h = h * 10 + cs[p] - '0';
                p++;
            }
            long try1 = this.pal(h, half, odd);
            long try2 = this.pal(h - 1, half, odd);
            long try3 = this.pal(h + 1, half, odd);
            long try4 = (long) Math.pow(10, len - 1) - 1;
            long try5 = (long) Math.pow(10, len) + 1;
            long ans = try2;
            ans = this.findAns(me, ans, try1);
            ans = this.findAns(me, ans, try3);
            ans = this.findAns(me, ans, try4);
            ans = this.findAns(me, ans, try5);
            return String.valueOf(ans);
        }

        private long findAns(long me, long ans, long other) {
            if (me != other) {
                if (Math.abs(me - ans) > Math.abs(me - other)) {
                    ans = other;
                } else if (Math.abs(me - ans) == Math.abs(me - other)) {
                    ans = Math.min(ans, other);
                }
            }
            return ans;
        }

        private long pal(long try1, long len, boolean odd) {
            len -= odd ? 1 : 0;
            long basic = (long) Math.pow(10, len);
            long ans = try1 * basic;
            long mirror = 0;
            try1 = odd ? try1 / 10 : try1;
            while (try1 > 0) {
                long cur = try1 % 10;
                mirror = mirror * 10 + cur;
                try1 /= 10;
            }
            return ans + mirror;
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[1,2,3]");
        System.out.println(solution.toString());
    }

    public static void main(String[] args) throws Exception {
        LC564 an = new LC564();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
